package com.example.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.entity.AutoEntity;
import com.example.util.AutoServiceUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Map;

@Controller
public class AutoController {

    @RequestMapping(value = "/auto",method = RequestMethod.POST)
    public String auto(ModelAndView model, AutoEntity autoEntity,
                       HttpServletRequest request) {
        System.out.println(JSONObject.toJSONString(autoEntity));
        Map<String,String> map = autoEntity.getMap();
        String cfn = map.get("cfileName");
        String []cf = cfn.split(",");
        for(String s:cf){
            map.get(s);
        }
//        String filePath =
//                this.getClass().getResource("/").getPath().replaceAll("/target/classes","");
        String filePath = "D:\\yihe_work\\qiklwork\\xiye-esc\\xiye-operate";
        //当前项目下路径
        File file = new File(filePath);

        String fileName = map.get("name");
        System.out.println(fileName);
        Map<String,String> fileMap = AutoServiceUtil.getFileMap(file,fileName,cf);
        for (Map.Entry<String, String> entry : fileMap.entrySet()) {
            System.out.println(entry.getKey()+":"+entry.getValue());
            try {
                RandomAccessFile accessFile = new RandomAccessFile(entry.getValue(), "rw");
                System.out.println(accessFile.length());
                accessFile.seek(accessFile.length()); // 定位文件指针所指的位置
                long pos = accessFile.length(); // 定位文件尾
                boolean bl = true;
                while (bl) {
                    --pos; // 一个字符一个字符的向前移动指针
                    // 判断文件是否到达头
                    accessFile.seek(pos); // 定位文件指针所指的位置
                    if (accessFile.readLine().indexOf("}") > -1) { // 如果是换行符,
                        System.out.println("++++++++++" + pos);
                        // 就可以读取该行了
                        System.out.println(accessFile.readLine());
                        bl = false;
                    }

                }
                System.out.println("------------" + pos);
                accessFile.seek(pos);
                accessFile.write(map.get(entry.getKey()).getBytes());
                accessFile.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "modules/auto";
    }
}
